import SockJS from 'sockjs-client'
import { Stomp } from '@stomp/stompjs'
import { ElMessage } from 'element-plus'
import { getUserToken, getUserInfo } from './auth'

/**
 * WebSocket聊天连接管理类
 */
class ChatWebSocket {
  constructor() {
    this.stompClient = null
    this.connected = false
    this.reconnectAttempts = 0
    this.maxReconnectAttempts = 5
    this.reconnectInterval = 3000
    this.messageHandlers = new Map()
    this.unreadHandlers = new Map()
    this.notificationHandlers = new Map()
    this.connectionHandlers = []
  }

  /**
   * 连接WebSocket
   */
  connect() {
    return new Promise((resolve, reject) => {
      try {
        const token = getUserToken()
        const userInfo = getUserInfo()
        
        if (!token || !userInfo) {
          reject(new Error('用户未登录'))
          return
        }

        // 创建SockJS连接，添加token参数
        const wsUrl = import.meta.env.DEV ? '/housingHub/ws/chat' : 'http://localhost:8085/housingHub/ws/chat'
        const socket = new SockJS(`${wsUrl}?token=${encodeURIComponent(token)}`)
        
        // 创建STOMP客户端
        this.stompClient = Stomp.over(socket)
        
        // 设置调试信息 (生产环境可关闭)
        this.stompClient.debug = import.meta.env.DEV ? console.log : () => {}

        // 连接到服务器
        this.stompClient.connect(
          { 
            'info': token,  // 传递token用于身份验证
            'userId': userInfo.id 
          },
          (frame) => {
            console.log('WebSocket连接成功:', frame)
            this.connected = true
            this.reconnectAttempts = 0
            
            // 订阅个人消息队列
            this.subscribeToPersonalQueue(userInfo.id)
            
            // 通知连接成功
            this.notifyConnectionHandlers(true)
            
            resolve(frame)
          },
          (error) => {
            console.error('WebSocket连接失败:', error)
            this.connected = false
            this.handleConnectionError(error)
            reject(error)
          }
        )
      } catch (error) {
        console.error('创建WebSocket连接时出错:', error)
        reject(error)
      }
    })
  }

  /**
   * 订阅个人消息队列
   */
  subscribeToPersonalQueue(userId) {
    if (!this.stompClient || !this.connected) {
      console.warn('WebSocket未连接，无法订阅消息队列')
      return
    }

    // 订阅聊天消息
    this.stompClient.subscribe(`/user/${userId}/queue/chat`, (message) => {
      try {
        const chatMessage = JSON.parse(message.body)
        console.log('收到聊天消息:', chatMessage)
        
        // 通知所有消息处理器
        this.messageHandlers.forEach((handler) => {
          try {
            handler(chatMessage)
          } catch (error) {
            console.error('消息处理器执行出错:', error)
          }
        })
      } catch (error) {
        console.error('解析聊天消息失败:', error)
      }
    })

    // 订阅未读消息数量更新
    this.stompClient.subscribe(`/user/${userId}/queue/unread`, (message) => {
      try {
        const unreadData = JSON.parse(message.body)
        console.log('收到未读消息更新:', unreadData)

        // 通知所有未读消息处理器
        this.unreadHandlers.forEach((handler) => {
          try {
            handler(unreadData)
          } catch (error) {
            console.error('未读消息处理器执行出错:', error)
          }
        })
      } catch (error) {
        console.error('解析未读消息数据失败:', error)
      }
    })

    // 订阅系统通知
    this.stompClient.subscribe(`/user/${userId}/queue/notification`, (message) => {
      try {
        const notification = JSON.parse(message.body)
        console.log('收到系统通知:', notification)

        // 显示系统通知
        ElMessage({
          message: notification.title || notification.content,
          type: 'info',
          duration: 5000,
          showClose: true
        })

        // 通知系统通知处理器
        this.notificationHandlers.forEach((handler) => {
          try {
            handler(notification)
          } catch (error) {
            console.error('系统通知处理器执行出错:', error)
          }
        })
      } catch (error) {
        console.error('解析系统通知失败:', error)
      }
    })

    // 订阅错误消息
    this.stompClient.subscribe(`/user/${userId}/queue/error`, (message) => {
      try {
        const errorMsg = typeof message.body === 'string' ? message.body : JSON.parse(message.body)
        console.error('收到WebSocket错误:', errorMsg)

        ElMessage({
          message: errorMsg.message || errorMsg,
          type: 'error',
          duration: 3000
        })
      } catch (error) {
        console.error('解析错误消息失败:', error)
      }
    })
  }

  /**
   * 发送消息 (通过WebSocket)
   */
  sendMessage(messageData) {
    if (!this.stompClient || !this.connected) {
      throw new Error('WebSocket未连接')
    }

    try {
      this.stompClient.send('/housinghub/chat/send', {}, JSON.stringify(messageData))
      console.log('通过WebSocket发送消息:', messageData)
    } catch (error) {
      console.error('发送消息失败:', error)
      throw error
    }
  }

  /**
   * 标记消息为已读 (通过WebSocket)
   */
  markAsRead(sessionId) {
    if (!this.stompClient || !this.connected) {
      console.warn('WebSocket未连接，无法标记已读')
      return
    }

    try {
      this.stompClient.send('/housinghub/chat/read', {}, JSON.stringify(sessionId))
      console.log('通过WebSocket标记已读:', sessionId)
    } catch (error) {
      console.error('标记已读失败:', error)
    }
  }

  /**
   * 断开连接
   */
  disconnect() {
    if (this.stompClient && this.connected) {
      this.stompClient.disconnect(() => {
        console.log('WebSocket连接已断开')
        this.connected = false
        this.notifyConnectionHandlers(false)
      })
    }
  }

  /**
   * 处理连接错误
   */
  handleConnectionError(error) {
    console.error('WebSocket连接错误:', error)
    
    if (this.reconnectAttempts < this.maxReconnectAttempts) {
      this.reconnectAttempts++
      console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})...`)
      
      setTimeout(() => {
        this.connect().catch((err) => {
          console.error('重连失败:', err)
        })
      }, this.reconnectInterval)
    } else {
      ElMessage.error('聊天连接失败，请刷新页面重试')
      this.notifyConnectionHandlers(false)
    }
  }

  /**
   * 添加消息处理器
   */
  addMessageHandler(id, handler) {
    this.messageHandlers.set(id, handler)
  }

  /**
   * 移除消息处理器
   */
  removeMessageHandler(id) {
    this.messageHandlers.delete(id)
  }

  /**
   * 添加未读消息处理器
   */
  addUnreadHandler(id, handler) {
    this.unreadHandlers.set(id, handler)
  }

  /**
   * 移除未读消息处理器
   */
  removeUnreadHandler(id) {
    this.unreadHandlers.delete(id)
  }

  /**
   * 添加系统通知处理器
   */
  addNotificationHandler(id, handler) {
    this.notificationHandlers.set(id, handler)
  }

  /**
   * 移除系统通知处理器
   */
  removeNotificationHandler(id) {
    this.notificationHandlers.delete(id)
  }

  /**
   * 添加连接状态处理器
   */
  addConnectionHandler(handler) {
    this.connectionHandlers.push(handler)
  }

  /**
   * 通知连接状态处理器
   */
  notifyConnectionHandlers(connected) {
    this.connectionHandlers.forEach((handler) => {
      try {
        handler(connected)
      } catch (error) {
        console.error('连接状态处理器执行出错:', error)
      }
    })
  }

  /**
   * 获取连接状态
   */
  isConnected() {
    return this.connected
  }
}

// 创建全局WebSocket实例
const chatWebSocket = new ChatWebSocket()

export default chatWebSocket
